/* eslint-disable react-native/no-inline-styles */
import React, { useRef, useState, useCallback, useEffect } from 'react';
import {
  View,
  ScrollView,
  FlatList,
  TouchableOpacity,
  Text,
  StyleSheet,
  Dimensions,
  ViewStyle,
  TextStyle,
  LayoutChangeEvent,
  NativeSyntheticEvent,
  NativeScrollEvent,
  ListRenderItemInfo,
} from 'react-native';

const { width: SCREEN_WIDTH } = Dimensions.get('window');

// ==================== 类型定义 ====================

export interface TabItem {
  key: string;
  label?: string; // 简单文字标签
  renderLabel?: (active: boolean) => React.ReactElement; // 自定义标签组件
  badge?: number | string | boolean; // 徽章：数字、文字或红点
  disabled?: boolean; // 是否禁用
  renderContent: () => React.ReactElement; // 页面内容（必需）
}

export interface TabViewProps {
  tabs: TabItem[];
  initialIndex?: number;

  // 标签栏配置
  tabBarPosition?: 'top' | 'bottom';
  tabBarStyle?: ViewStyle;
  tabBarBackgroundColor?: string;

  // 标签项样式
  tabItemStyle?: ViewStyle;
  tabItemActiveStyle?: ViewStyle;
  tabLabelStyle?: TextStyle;
  tabLabelActiveStyle?: TextStyle;

  // Badge 样式
  badgeStyle?: ViewStyle;
  badgeTextStyle?: TextStyle;

  // 页面配置
  lazy?: boolean; // 是否懒加载
  swipeEnabled?: boolean; // 是否允许手势滑动

  // 回调
  onIndexChange?: (index: number) => void;
}

interface TabLabelViewProps {
  tabs: TabItem[];
  activeIndex: number;
  onTabPress: (index: number) => void;
  tabBarStyle?: ViewStyle;
  tabBarBackgroundColor?: string;
  tabItemStyle?: ViewStyle;
  tabItemActiveStyle?: ViewStyle;
  tabLabelStyle?: TextStyle;
  tabLabelActiveStyle?: TextStyle;
  badgeStyle?: ViewStyle;
  badgeTextStyle?: TextStyle;
}

interface TabPageViewProps {
  tabs: TabItem[];
  activeIndex: number;
  onIndexChange: (index: number) => void;
  lazy: boolean;
  swipeEnabled: boolean;
  pageWidth: number;
}

// ==================== TabLabelView 组件 ====================

const TabLabelView: React.FC<TabLabelViewProps> = ({
  tabs,
  activeIndex,
  onTabPress,
  tabBarStyle,
  tabBarBackgroundColor = '#ffffff',
  tabItemStyle,
  tabItemActiveStyle,
  tabLabelStyle,
  tabLabelActiveStyle,
  badgeStyle,
  badgeTextStyle,
}) => {
  const scrollViewRef = useRef<ScrollView>(null);
  const tabRefs = useRef<Map<number, { x: number; width: number }>>(new Map());

  // 测量每个标签的位置和宽度
  const handleTabLayout = useCallback(
    (index: number, event: LayoutChangeEvent) => {
      const { x, width } = event.nativeEvent.layout;
      tabRefs.current.set(index, { x, width });
    },
    [],
  );

  // 当激活的标签改变时，自动滚动到居中位置
  useEffect(() => {
    const tabLayout = tabRefs.current.get(activeIndex);
    if (tabLayout && scrollViewRef.current) {
      const { x, width } = tabLayout;
      const centerOffset = x + width / 2 - SCREEN_WIDTH / 2;
      scrollViewRef.current.scrollTo({
        x: Math.max(0, centerOffset),
        animated: true,
      });
    }
  }, [activeIndex]);

  // 渲染 Badge
  const renderBadge = (badge?: number | string | boolean) => {
    if (!badge) return null;

    const isRedDot = badge === true;
    return (
      <View style={[styles.badge, isRedDot && styles.badgeDot, badgeStyle]}>
        {!isRedDot && (
          <Text style={[styles.badgeText, badgeTextStyle]}>
            {typeof badge === 'number' && badge > 99 ? '99+' : badge}
          </Text>
        )}
      </View>
    );
  };

  // 渲染单个标签
  const renderTab = (item: TabItem, index: number) => {
    const isActive = index === activeIndex;
    const isDisabled = item.disabled;

    return (
      <TouchableOpacity
        key={item.key}
        activeOpacity={0.7}
        disabled={isDisabled}
        onPress={() => !isDisabled && onTabPress(index)}
        onLayout={event => handleTabLayout(index, event)}
      >
        <View
          style={[
            styles.tabItem,
            tabItemStyle,
            isActive && styles.tabItemActive,
            isActive && tabItemActiveStyle,
            isDisabled && styles.tabItemDisabled,
          ]}
        >
          {/* 自定义标签或默认文字 */}
          {item.renderLabel ? (
            item.renderLabel(isActive)
          ) : (
            <Text
              style={[
                styles.tabLabel,
                tabLabelStyle,
                isActive && styles.tabLabelActive,
                isActive && tabLabelActiveStyle,
                isDisabled && styles.tabLabelDisabled,
              ]}
            >
              {item.label || item.key}
            </Text>
          )}

          {/* Badge */}
          {renderBadge(item.badge)}
        </View>
      </TouchableOpacity>
    );
  };

  return (
    <View
      style={[
        styles.tabBar,
        { backgroundColor: tabBarBackgroundColor },
        tabBarStyle,
      ]}
    >
      <ScrollView
        ref={scrollViewRef}
        horizontal
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={styles.tabBarContent}
      >
        {tabs.map((item, index) => renderTab(item, index))}
      </ScrollView>
    </View>
  );
};

// ==================== TabPageView 组件 ====================

const TabPageView: React.FC<TabPageViewProps> = ({
  tabs,
  activeIndex,
  onIndexChange,
  lazy,
  swipeEnabled,
  pageWidth,
}) => {
  const flatListRef = useRef<FlatList>(null);
  const [loadedTabs, setLoadedTabs] = useState<Set<number>>(
    new Set([activeIndex]),
  );

  // Effect 1: 处理懒加载标记
  useEffect(() => {
    if (lazy && !loadedTabs.has(activeIndex)) {
      setLoadedTabs(prev => new Set(prev).add(activeIndex));
    }
  }, [activeIndex, lazy, loadedTabs]); // 不依赖 loadedTabs

  // Effect 2: 处理滚动（需要等待渲染完成）
  useEffect(() => {
    // 懒加载模式下，确保目标页面已加载
    if (lazy && !loadedTabs.has(activeIndex)) {
      return; // 等待下一次渲染
    }

    if (flatListRef.current) {
      // 可以考虑用 setTimeout 确保渲染完成
      setTimeout(() => {
        flatListRef.current?.scrollToIndex({
          index: activeIndex,
          animated: true,
        });
      }, 0); // 或者 10-50ms
    }
  }, [activeIndex, lazy, loadedTabs]); // 这次 loadedTabs 是必要的

  // 处理滚动结束，同步当前页面索引
  const handleMomentumScrollEnd = useCallback(
    (event: NativeSyntheticEvent<NativeScrollEvent>) => {
      const offsetX = event.nativeEvent.contentOffset.x;
      const index = Math.round(offsetX / pageWidth);
      if (index !== activeIndex && index >= 0 && index < tabs.length) {
        onIndexChange(index);
      }
    },
    [pageWidth, activeIndex, tabs.length, onIndexChange],
  );

  // 处理拖拽结束（Android 可能需要）
  const handleScrollEndDrag = useCallback(
    (event: NativeSyntheticEvent<NativeScrollEvent>) => {
      const offsetX = event.nativeEvent.contentOffset.x;
      const index = Math.round(offsetX / pageWidth);
      if (index !== activeIndex && index >= 0 && index < tabs.length) {
        onIndexChange(index);
      }
    },
    [pageWidth, activeIndex, tabs.length, onIndexChange],
  );

  // 处理 scrollToIndex 失败的情况
  const handleScrollToIndexFailed = useCallback((info: any) => {
    console.warn('ScrollToIndex failed:', info);
    // 延迟重试
    setTimeout(() => {
      if (flatListRef.current) {
        flatListRef.current.scrollToIndex({
          index: info.index,
          animated: false,
        });
      }
    }, 100);
  }, []);

  // 获取固定布局（性能优化）
  const getItemLayout = useCallback(
    (_data: any, index: number) => ({
      length: pageWidth,
      offset: pageWidth * index,
      index,
    }),
    [pageWidth],
  );

  // 渲染单个页面
  const renderPage = useCallback(
    ({ item, index }: ListRenderItemInfo<TabItem>) => {
      // 懒加载逻辑：未加载过的页面不渲染
      const shouldRender = !lazy || loadedTabs.has(index);

      return (
        <View style={[styles.page, { width: pageWidth }]}>
          {shouldRender ? item.renderContent() : <View style={{ flex: 1 }} />}
        </View>
      );
    },
    [lazy, loadedTabs, pageWidth],
  );

  return (
    <FlatList
      ref={flatListRef}
      data={tabs}
      renderItem={renderPage}
      keyExtractor={item => item.key}
      horizontal
      pagingEnabled
      showsHorizontalScrollIndicator={false}
      scrollEnabled={swipeEnabled}
      onMomentumScrollEnd={handleMomentumScrollEnd}
      onScrollEndDrag={handleScrollEndDrag}
      onScrollToIndexFailed={handleScrollToIndexFailed}
      getItemLayout={getItemLayout}
      initialScrollIndex={activeIndex}
      bounces={false}
      scrollEventThrottle={16}
    />
  );
};

// ==================== TabView 主组件 ====================

const TabView: React.FC<TabViewProps> = ({
  tabs,
  initialIndex = 0,
  tabBarPosition = 'top',
  tabBarStyle,
  tabBarBackgroundColor,
  tabItemStyle,
  tabItemActiveStyle,
  tabLabelStyle,
  tabLabelActiveStyle,
  badgeStyle,
  badgeTextStyle,
  lazy = false,
  swipeEnabled = true,
  onIndexChange,
}) => {
  const [activeIndex, setActiveIndex] = useState(
    Math.max(0, Math.min(initialIndex, tabs.length - 1)),
  );
  const [pageWidth, setPageWidth] = useState(SCREEN_WIDTH);

  // 处理容器布局变化（支持屏幕旋转等）
  const handleContainerLayout = useCallback((event: LayoutChangeEvent) => {
    const { width } = event.nativeEvent.layout;
    setPageWidth(width);
  }, []);

  // 处理标签点击
  const handleTabPress = useCallback(
    (index: number) => {
      if (index !== activeIndex) {
        setActiveIndex(index);
        onIndexChange?.(index);
      }
    },
    [activeIndex, onIndexChange],
  );

  // 处理页面切换
  const handlePageChange = useCallback(
    (index: number) => {
      if (index !== activeIndex) {
        setActiveIndex(index);
        onIndexChange?.(index);
      }
    },
    [activeIndex, onIndexChange],
  );

  console.log('activeIndex', activeIndex);

  // 标签栏组件
  const tabLabelView = (
    <TabLabelView
      tabs={tabs}
      activeIndex={activeIndex}
      onTabPress={handleTabPress}
      tabBarStyle={tabBarStyle}
      tabBarBackgroundColor={tabBarBackgroundColor}
      tabItemStyle={tabItemStyle}
      tabItemActiveStyle={tabItemActiveStyle}
      tabLabelStyle={tabLabelStyle}
      tabLabelActiveStyle={tabLabelActiveStyle}
      badgeStyle={badgeStyle}
      badgeTextStyle={badgeTextStyle}
    />
  );

  // 页面内容组件
  const tabPageView = (
    <TabPageView
      tabs={tabs}
      activeIndex={activeIndex}
      onIndexChange={handlePageChange}
      lazy={lazy}
      swipeEnabled={swipeEnabled}
      pageWidth={pageWidth}
    />
  );

  return (
    <View style={styles.container} onLayout={handleContainerLayout}>
      {tabBarPosition === 'top' && tabLabelView}
      {tabPageView}
      {tabBarPosition === 'bottom' && tabLabelView}
    </View>
  );
};

// ==================== 样式定义 ====================

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  // 标签栏样式
  tabBar: {
    height: 48,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: '#e0e0e0',
  },
  tabBarContent: {
    alignItems: 'center',
    paddingHorizontal: 8,
  },
  // 标签项样式
  tabItem: {
    paddingHorizontal: 16,
    height: 48,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 8,
    marginHorizontal: 4,
  },
  tabItemActive: {
    backgroundColor: '#e3f2fd', // 浅蓝色背景高亮
  },
  tabItemDisabled: {
    opacity: 0.4,
  },
  // 标签文字样式
  tabLabel: {
    fontSize: 15,
    color: '#666666',
    fontWeight: '500',
  },
  tabLabelActive: {
    color: '#1976d2', // 深蓝色文字
    fontWeight: '600',
  },
  tabLabelDisabled: {
    color: '#cccccc',
  },
  // Badge 样式
  badge: {
    position: 'absolute',
    top: 6,
    right: 8,
    backgroundColor: '#f44336',
    borderRadius: 10,
    minWidth: 18,
    height: 18,
    paddingHorizontal: 5,
    justifyContent: 'center',
    alignItems: 'center',
  },
  badgeDot: {
    minWidth: 8,
    height: 8,
    borderRadius: 4,
    paddingHorizontal: 0,
  },
  badgeText: {
    color: '#ffffff',
    fontSize: 11,
    fontWeight: 'bold',
  },
  // 页面样式
  page: {
    flex: 1,
  },
});

export default TabView;
